package com.toobigtofail.utility
{
	import Box2D.Common.Math.b2Vec2;
	
	import com.toobigtofail.entities.BuildingBlock;
	import com.toobigtofail.entities.Enemy;
	import com.toobigtofail.entities.Target;
	import com.toobigtofail.placeholders.Placeholder;
	import com.toobigtofail.placeholders.PlankPlaceholder;
	import com.toobigtofail.placeholders.WedgePlaceholder;
	import com.toobigtofail.shapes.Ball;
	import com.toobigtofail.shapes.Box;
	import com.toobigtofail.shapes.IShape;
	import com.toobigtofail.shapes.Octagon;
	import com.toobigtofail.shapes.Wedge;
	
	import flash.utils.ByteArray;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;

	public class LevelParser
	{
		private var _levels:Array;
		private var _currentLevel:int = 0;
		
		public function LevelParser(xmlReference:Class) {
			_levels = parseLevels(xmlReference);
		}
		
		public static function parseLevels(classReference:Class):Array {
			var file:ByteArray = new classReference;
			var xml:XML = new XML(file.readUTFBytes(file.length));
			
			return parseLevelXml(xml);
		}
		
		public static function parseLevelXml(levelXml:XML):Array {
			var levels:Array = new Array;
			for each (var level:XML in levelXml.level) {
				levels.push(new Level(level));
			}
			
			return levels;
		}
		
		public static function serializeLevels(levels:Array):XML {
			var xml:XML = <root/>;
			for each (var l:Level in levels) {
				xml.appendChild(l.serialize());
			}
			
			return xml;
		}
		
		public function resetLevel():Level {
			currentLevel.reset();
			return currentLevel;
		}
		
		public function hasNextLevel():Boolean {
			return _levels.length > _currentLevel+1
		}
		
		public function addLevels(levelXml:XML):void {
			for each (var level:Level in parseLevelXml(levelXml)) {
				trace("adding a level");
				_levels.push(level);
			}
		}
		
		public function get nextLevel():Level {
			if (_levels && _currentLevel+1 < _levels.length) {
				return _levels[++_currentLevel];
			}
			return null;
		}
		
		public function get currentLevel():Level {
		 	if (_levels && _currentLevel < _levels.length) {
				return _levels[_currentLevel];
			}
			return null;
		}
		
		public function get levels():Array { return _levels; }
		public function get numLevels():uint { return _levels.length; }
	}
}